# -*- coding: utf-8 -*-
from export.distributors.brain import Brain
from export.distributors.fotos import Fotos
from export.distributors.repka import Repka
from export.distributors.stack import Stack
from export.distributors.ugcontract import Ugcontract


class ImportIntoMagento():
    defaultHeader = '"attribute_set","category_ids","store","sku","name","brand_name","description","short_description","main_type","price","status","owner","visibility","type","weight","tax_class_id"'

    def __init__(self):
        pass

    configDistributor = {}
    rules = {}

    def importProducts(self, config):
        self.configDistributor = {'web.stek.com.ua': Stack(), 'fotos': Fotos(), 'ug': Ugcontract(), 'repka': Repka(),
                                  'brain': Brain()}
        distributorsProducts = {}
        products = []
        for key in config.keys():
            if key in self.configDistributor:
                b2b = self.configDistributor[key]
                b2b.rules = config[key]
                self.rules = config[key]
                for key_ in config[key].keys():
                    b2b.baseAttrib = b2b.getAttributeSets(config[key][key_][0])
                b2b.encodeRules()
                for categoryName in config[key]:
                    products_ = b2b.handlerHtmlCatalog(
                        definiteCategoryName=categoryName.decode('utf-8'))
                    products += products_
                distributorsProducts[key] = products
        if not products:
            return '', None
        return self.createImportFile(products), self.rules.keys()[0]

    def createImportFile(self, products):
        csvContent = self.defaultHeader
        attrs = []
        for attr in self.rules[self.rules.keys()[0]][1].keys():
            csvContent += ',\"' + self.rules[self.rules.keys()[0]][1][attr][0].encode('cp1251') + '\"'
            attrs.append(self.rules[self.rules.keys()[0]][1][attr][0].encode('cp1251'))
        if len(self.rules[self.rules.keys()[0]]) == 5:
            csvContent += ',\"' + self.rules[self.rules.keys()[0]][4].encode('cp1251') + '\"'
            attrs.append(self.rules[self.rules.keys()[0]][4])
        csvContent += '\r\n'
        try:
            temp = csvContent.encode('utf-8')
            csvContent = temp
        except UnicodeDecodeError:
            pass
        for product in products:
            if product['attrs']:
                csvContent += '"%s","%s","admin","%s","%s","%s","%s","%s","%s","%s","Отключено","user03","Каталог, поиск","simple","0","4"' % (
                    product['attr_set'].encode('utf-8'), product['categoryId'].encode('utf-8'),
                    product['sku'].encode('utf-8'),
                    product['name'].encode('utf-8'),
                    product['brand_name'].encode('utf-8'), product['descr'].encode('utf-8'),
                    product['short_descr'].encode('utf-8'), product['attr_set'].encode('utf-8'), str(product['price']))
                for attr in attrs:
                    try:
                        csvContent += ',\"' + product['new_attrs'][attr].encode('utf-8') + '\"'
                    except UnicodeDecodeError:
                        csvContent += ',\"' + product['new_attrs'][attr] + '\"'
                    except KeyError:
                        csvContent += ',\"\"'
                if products.index(product) != len(products) - 1:
                    csvContent += '\r\n'
        return csvContent
